<template>
  <div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button
          type="primary"
          icon="plus"
          @click="openDialog"
        >新增</el-button>
        <el-popover
          v-model:visible="deleteVisible"
          :disabled="!multipleSelection.length"
          placement="top"
          width="160"
        >
          <p>确定要删除吗？</p>
          <div style="text-align: right; margin-top: 8px;">
            <el-button
              type="primary"
              link
              @click="deleteVisible = false"
            >取消</el-button>
            <el-button
              type="primary"
              @click="onDelete"
            >确定</el-button>
          </div>
          <template #reference>
            <el-button
              icon="delete"
              style="margin-left: 10px;"
              :disabled="!multipleSelection.length"
              @click="deleteVisible = true"
            >删除</el-button>
          </template>
        </el-popover>
      </div>
      <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        row-key="ID"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          align="left"
          label="功效"
          prop="name"
          min-width="120"
        />
        <el-table-column
          align="left"
          label="操作"
        >
          <template #default="scope">
            <el-button
              type="primary"
              link
              icon="edit"
              class="table-button"
              @click="relevancy(scope.row)"
            >关联文章</el-button>
            <el-button
              type="primary"
              link
              icon="edit"
              class="table-button"
              @click="updateFdEfficacyFunc(scope.row)"
            >变更</el-button>
            <el-button
              type="primary"
              link
              icon="delete"
              @click="deleteRow(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="dialogFormVisible"
      :before-close="closeDialog"
      :title="type==='create'?'添加':'修改'"
      destroy-on-close
    >
      <el-scrollbar height="500px">
        <el-form
          ref="elFormRef"
          :model="formData"
          label-position="right"
          :rules="rule"
          label-width="80px"
        >
          <el-form-item
            label="功效:"
            prop="name"
          >
            <el-input
              v-model="formData.name"
              :clearable="true"
              placeholder="请输入功效"
            />
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button
            type="primary"
            @click="enterDialog"
          >确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-drawer
      v-model="drawer"
      direction="rtl"
    >
      <template #header>
        <div>
          <h4>关联文章</h4>
          <el-input
            v-model="filterText"
            placeholder="请输入搜索内容"
            clearable
          />
          <div class="flex gap-2 mt-2">
            <el-select
              v-model="levelOne"
              placeholder="请选择一级标题"
              clearable
            >
              <el-option
                v-for="item in levelOneOptions"
                :key="item.ID"
                :label="item.value"
                :value="item.ID"
              />
            </el-select>
            <el-select
              v-model="levelTwo"
              placeholder="请选择二级标题"
              clearable
            >
              <el-option
                  v-for="item in levelTwoOptions.filter(item=>levelOne?item.levelOneID === levelOne:true)"

                  :key="item.ID"
                :label="item.value"
                :value="item.ID"
              />
            </el-select>
            <el-select
              v-model="levelThree"
              placeholder="请选择三级标题"
              clearable
            >
              <el-option
                  v-for="item in levelThreeOptions.filter(item=>levelTwo?item.levelTwoID === levelTwo:true)"
                :key="item.ID"
                :label="item.value"
                :value="item.ID"
              />
            </el-select>
          </div>
        </div>

      </template>
      <template #default>
        <div>
          <el-tabs v-model="tag">
            <el-tab-pane
              label="图文"
              name="graphic"
            >
              <el-tree
                ref="treeRefGraphic"
                node-key="ID"
                :data="graphics"
                :filter-node-method="filterTree"
                :props="{
                  label: 'title',
                }"
                show-checkbox
              />
            </el-tab-pane>
            <el-tab-pane
              label="音频"
              name="audio"
            >
              <el-tree
                ref="treeRefAudio"
                node-key="ID"
                :data="audios"
                :filter-node-method="filterTree"
                :props="{
                  label: 'title',
                }"
                show-checkbox
              />
            </el-tab-pane>
            <el-tab-pane
              label="视频"
              name="video"
            >
              <el-tree
                ref="treeRefVideo"
                node-key="ID"
                :data="videos"
                :filter-node-method="filterTree"
                :props="{
                  label: 'title',
                }"
                show-checkbox
              />
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">取消</el-button>
          <el-button
            type="primary"
            @click="confirmClick"
          >确定</el-button>
        </div>
      </template>
    </el-drawer>

  </div>
</template>

<script setup>
import {
  createFdEfficacy,
  deleteFdEfficacy,
  deleteFdEfficacyByIds,
  updateFdEfficacy,
  findFdEfficacy,
  getFdEfficacyList
} from '@/api/fdEfficacy'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatBoolean, filterDict, ReturnArrImg, onDownloadFile } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, watch } from 'vue'
import { getFdArticleGraphicList } from '@/api/fdArticleGraphic'
import { getFdArticleAudioList } from '@/api/fdArticleAudio'
import { getFdArticleVideoList } from '@/api/fdArticleVideo'
import { getFdEfficacyGraphic, setFdEfficacyGraphic } from '@/api/fdEfficacy'
import { getLevelOneList } from '@/api/levelOne'
import { getLevelTwoList } from '@/api/levelTwo'
import { getLevelThreeList } from '@/api/levelThree'

defineOptions({
  name: 'FdEfficacy'
})

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
  name: '',
})

// 验证规则
const rule = reactive({
})

const searchRule = reactive({
  createdAt: [
    { validator: (rule, value, callback) => {
      if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
        callback(new Error('请填写结束日期'))
      } else if (!searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt) {
        callback(new Error('请填写开始日期'))
      } else if (searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt && (searchInfo.value.startCreatedAt.getTime() === searchInfo.value.endCreatedAt.getTime() || searchInfo.value.startCreatedAt.getTime() > searchInfo.value.endCreatedAt.getTime())) {
        callback(new Error('开始日期应当早于结束日期'))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ],
})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})
const tag = ref('graphic')

// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    pageSize.value = 10
    getTableData()
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async() => {
  const table = await getFdEfficacyList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async() => {
}

// 获取需要的字典 可能为空 按需保留
setOptions()

// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 删除行
const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteFdEfficacyFunc(row)
  })
}

// 批量删除控制标记
const deleteVisible = ref(false)

// 多选删除
const onDelete = async() => {
  const ids = []
  if (multipleSelection.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的数据'
    })
    return
  }
  multipleSelection.value &&
        multipleSelection.value.map(item => {
          ids.push(item.ID)
        })
  const res = await deleteFdEfficacyByIds({ ids })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === ids.length && page.value > 1) {
      page.value--
    }
    deleteVisible.value = false
    getTableData()
  }
}

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

// 更新行
const updateFdEfficacyFunc = async(row) => {
  const res = await findFdEfficacy({ ID: row.ID })
  type.value = 'update'
  if (res.code === 0) {
    formData.value = res.data.refdEfficacy
    dialogFormVisible.value = true
  }
}

// 删除行
const deleteFdEfficacyFunc = async(row) => {
  const res = await deleteFdEfficacy({ ID: row.ID })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    getTableData()
  }
}

// 弹窗控制标记
const dialogFormVisible = ref(false)

// 查看详情控制标记
const detailShow = ref(false)

// 打开详情弹窗
const openDetailShow = () => {
  detailShow.value = true
}

// 打开详情
const getDetails = async(row) => {
  // 打开弹窗
  const res = await findFdEfficacy({ ID: row.ID })
  if (res.code === 0) {
    formData.value = res.data.refdEfficacy
    openDetailShow()
  }
}

// 关闭详情弹窗
const closeDetailShow = () => {
  detailShow.value = false
  formData.value = {
    name: '',
  }
}

// 打开弹窗
const openDialog = () => {
  type.value = 'create'
  dialogFormVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    name: '',
  }
}
// 弹窗确定
const enterDialog = async() => {
  elFormRef.value?.validate(async(valid) => {
    if (!valid) return
    let res
    switch (type.value) {
      case 'create':
        res = await createFdEfficacy(formData.value)
        break
      case 'update':
        res = await updateFdEfficacy(formData.value)
        break
      default:
        res = await createFdEfficacy(formData.value)
        break
    }
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '创建/更改成功'
      })
      closeDialog()
      getTableData()
    }
  })
}

const filterText = ref('')

const active = ref({})

const drawer = ref(false)

const graphics = ref([])
const audios = ref([])
const videos = ref([])

const treeRefGraphic = ref(null)
const treeRefAudio = ref(null)
const treeRefVideo = ref(null)

const filterGraphics = () => {
  let res = graphics.value
  if (filterText.value) {
    res = graphics.value.filter(item => item.title.includes(filterText.value))
  }
  if (levelOne.value) {
    res = res.filter(item => item.levelOneID === levelOne.value)
  }
  if (levelTwo.value) {
    res = res.filter(item => item.levelTwoID === levelTwo.value)
  }
  if (levelThree.value) {
    res = res.filter(item => item.levelThreeID === levelThree.value)
  }
  return res
}

const filterAudios = () => {
  let res = audios.value
  if (filterText.value) {
    res = audios.value.filter(item => item.title.includes(filterText.value))
  }
  if (levelOne.value) {
    res = res.filter(item => item.levelOneID === levelOne.value)
  }
  if (levelTwo.value) {
    res = res.filter(item => item.levelTwoID === levelTwo.value)
  }
  if (levelThree.value) {
    res = res.filter(item => item.levelThreeID === levelThree.value)
  }
  return res
}

const filterVideos = () => {
  let res = videos.value
  if (filterText.value) {
    res = videos.value.filter(item => item.title.includes(filterText.value))
  }
  if (levelOne.value) {
    res = res.filter(item => item.levelOneID === levelOne.value)
  }
  if (levelTwo.value) {
    res = res.filter(item => item.levelTwoID === levelTwo.value)
  }
  if (levelThree.value) {
    res = res.filter(item => item.levelThreeID === levelThree.value)
  }
  return res
}

const getGraphic = async() => {
  const res = await getFdArticleGraphicList()
  const res2 = await getFdArticleAudioList()
  const res3 = await getFdArticleVideoList()
  if (res.code === 0) {
    graphics.value = res.data.list
  }
  if (res2.code === 0) {
    audios.value = res2.data.list
  }
  if (res3.code === 0) {
    videos.value = res3.data.list
  }
}

getGraphic()

const relevancy = async(row) => {
  active.value = row
  drawer.value = true
  const res = await getFdEfficacyGraphic({ fd_efficacy_id: row.ID })
  if (res.code === 0) {
    const graphicIds = []
    const audioIds = []
    const videoIds = []
    res.data?.forEach(item => {
      if (item.type === 'graphic') {
        graphicIds.push(item.article_id)
      }
      if (item.type === 'audio') {
        audioIds.push(item.article_id)
      }
      if (item.type === 'video') {
        videoIds.push(item.article_id)
      }
    })
    treeRefGraphic.value.setCheckedKeys(graphicIds)
    treeRefAudio.value.setCheckedKeys(audioIds)
    treeRefVideo.value.setCheckedKeys(videoIds)
  }
}
const confirmClick = async() => {
  filterText.value = ''
  levelOne.value = undefined
  levelTwo.value = undefined
  levelThree.value = undefined

  const graphicIds = treeRefGraphic.value.getCheckedKeys()
  const audioIds = treeRefAudio.value.getCheckedKeys()
  const videoIds = treeRefVideo.value.getCheckedKeys()

  const res = await setFdEfficacyGraphic({
    fd_efficacy_id: active.value.ID,
    graphic_id: graphicIds,
    audio_id: audioIds,
    video_id: videoIds,
  })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '关联成功'
    })
    drawer.value = false
  }
}

const levelOne = ref()
const levelTwo = ref()
const levelThree = ref()

const levelOneOptions = ref([])
const levelTwoOptions = ref([])
const levelThreeOptions = ref([])

const getLevelOptions = async() => {
  const res1 = await getLevelOneList()
  if (res1.code === 0) {
    levelOneOptions.value = res1.data.list
  }
  const res2 = await getLevelTwoList()
  if (res2.code === 0) {
    levelTwoOptions.value = res2.data.list
  }
  const res3 = await getLevelThreeList()
  if (res3.code === 0) {
    levelThreeOptions.value = res3.data.list
  }
}

getLevelOptions()


const filterTree = (_,tree) => {
  let flag = true
  if (filterText.value) {
    flag = tree.title.includes(filterText.value)
  }
  if (levelOne.value) {
    flag = tree.levelOneID === levelOne.value
  }
  if (levelTwo.value) {
    flag = tree.levelTwoID === levelTwo.value
  }
  if (levelThree.value) {
    flag = tree.levelThreeID === levelThree.value
  }
  return flag
}



watch(()=>[filterText.value,levelOne.value,levelTwo.value,levelThree.value],()=>{
  treeRefGraphic.value?.filter()
  treeRefAudio.value?.filter()
  treeRefVideo.value?.filter()
})


</script>

<style>
.el-drawer__header{
  margin-bottom: 0;
}
</style>
